﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using HRM.HRMServiceProxy;
using Microsoft.Reporting.WinForms;
using HRM.BusinessLogic;

namespace HRM
{
    public partial class frmChotSo : FormBase
    {
        int _department_ID;
        int _branch_ID;

        int _month = DateTime.Now.Month;
        int _year = DateTime.Now.Year;
        bool _loadedData = false;
        
        IssueInsBookClient _wcfIB;
        BranchClient wcfBranch;
        DepartmentClient wcfDepartment;
        DoiSoClient wcfDoiSo;
        EmployeeClient _wcfEmpl;
        RoleRightInfo listRole;
        MainServiceClient wcLWain;
        UserClient wcfUser;
        string _selectedID = ",";
        string _SoBHXH = "";

        public frmChotSo()
        {
            InitializeComponent();
            //
            wcfBranch = Service.Branch();
            wcfDepartment = Service.Department();
            _wcfIB = Service.IssueInsBook();
            wcLWain = Service.MainService();
            wcfDoiSo = Service.DoiSo();
            listRole = UIParamater.Quyen_DeNghiCapSoBH;
            _wcfEmpl = Service.Employee();
            wcfUser = Service.User();

            UISetting.LoadTreeView3(ref tvBranch);

            //
            btnPrint.Enabled = listRole.Create;            
            LayDanhSachLoaiDoiSo();

            btnChoDuyet.Visible = cbxLoaiDoiSo.ComboBox.SelectedValue.ToString() == "T";
            btnDuyet.Visible = cbxLoaiDoiSo.ComboBox.SelectedValue.ToString() == "P" && Program.isChuyenQuan;

            Bind_Data();
            
            showhide_commandbutton();
        }


        public override void Show_Form()
        {
            this.Show();
        }

        protected override void Init_Control()
        {
            Init_Grid();
            //
            Bind_Data();
        }


        //Hiển thị loại trạng thái
        private void LayDanhSachLoaiDoiSo()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Ma");
            dt.Columns.Add("Ten");

            dt.Rows.Add("T", "DS thôi đóng");
            dt.Rows.Add("P", "Chờ duyệt chốt sổ");
            dt.Rows.Add("D", "Đã duyệt chốt sổ");
            //dt.Rows.Add("C", "Đã cấp sổ / đổi sổ");

            cbxLoaiDoiSo.ComboBox.DisplayMember = "Ten";
            cbxLoaiDoiSo.ComboBox.ValueMember = "Ma";
            cbxLoaiDoiSo.ComboBox.DataSource = dt;
            cbxLoaiDoiSo.ComboBox.SelectedValue = "T";
        }

        private void LoadLanguage()
        {
            if (this.Tag != null)
                this.TabText = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
        }

        //Grid hiển thị danh sách
        DataGridHandle m_GridHandle;
        private void Init_Grid()
        {
            dtgData.Columns.Clear();
            //Thêm cột Checkbox
            DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
            col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            col.Name = "Check";
            col.HeaderText = "Chọn";
            col.Width = 50;
            col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dtgData.Columns.Add(col);
            col.Visible = true;

            List<DataGridViewColumn> arrColumn = new List<DataGridViewColumn>();
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("STT", "RN", 50));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số sổ BH", "Employee_SiBookNo", 80));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Họ và tên", "Employee_FullName", 120));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Ngày sinh", "Employee_DateOfBirth", 120));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("PA", "Detail_InsTypeCode", 40));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Employee_Id", "Employee_Id", 0, "", false));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("ChotSo_Id", "ChotSo_Id", 0));

            m_GridHandle = FormGlobals.Grid_Init(dtgData, arrColumn, "", 1);
        }

        //Lấy danh sách
        private void Bind_Data()
        {
            string sType = cbxLoaiDoiSo.ComboBox.SelectedValue.ToString();

            DataTable dt =null ;
            
            switch(sType)
            {
                case "T":
                    dt= Detail_Controller.Instance().DSKhongThamGiaBH(Program.strBranchCode);
                break;
                case "P":
                case "D":
                dt = ChotSo_Controller.Instance().ChotSo_GetAll(Program.intBranchID, sType);
                dt.Columns["Check"].DefaultValue = false;
                break;
            }

            if (txtKeyWord.Text != "")
                dt.DefaultView.RowFilter =  "Employee_SiBookNo Like '%" + txtKeyWord.Text + "%' OR Employee_FullName Like '%" + txtKeyWord.Text + "%'";
            //
            dtgData.DataSource = dt;
        }

        private void GetSelectedID()
        {
            foreach (DataGridViewRow row in dtgData.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value))
                {
                    if (!_selectedID.Contains("," + row.Cells["Employee_ID"].Value.ToString() + ","))
                    {
                        _selectedID += row.Cells["Employee_ID"].Value.ToString() + ",";
                    }
                }
                else
                {
                    string sOld = "," + row.Cells["Employee_ID"].Value.ToString() + ",";
                    if (_selectedID.Contains(sOld))
                        _selectedID = _selectedID.Replace(sOld, ",");
                }
            }
        }
        
        //Lọc danh sách theo phòng ban
        private void tvBranch_AfterSelect(object sender, TreeViewEventArgs e)
        {
            txtKeyWord.Text = "";
            if (e.Node.Level == 0)
            {
                if (Program.isAdmin || Program.isViewAll)
                {
                    _branch_ID = 0;
                    _department_ID = 0;
                }
                else
                    _branch_ID = Program.intBranchID;
                //
                Bind_Data();
            }
            else if (e.Node.Level == 1)
            {
                _branch_ID = Convert.ToInt32(e.Node.Tag);
                _department_ID = 0;
                Bind_Data();
            }
            else if (e.Node.Level >= 2)
            {
                _department_ID = Convert.ToInt32(e.Node.Tag);
                _branch_ID = Convert.ToInt32(e.Node.Parent.Tag);
                Bind_Data();
            }
        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_loadedData)
            {
                Bind_Data();
            }
        }

        private void txtKeyWord_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnFind_Click(null, null);
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            _selectedID = "";
            Bind_Data();
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            if (dtgData.SelectedRows.Count > 0)
            {
                int _EID = Convert.ToInt32(dtgData.CurrentRow.Cells["Employee_ID"].Value);
                frmEmployeeInfo f = new frmEmployeeInfo(_EID, _branch_ID, _department_ID, 8, listRole);
                f.ShowDialog();
            }
        }

        private void cbmonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_loadedData)
            {
                Bind_Data();
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            _selectedID = "";
            GetSelectedID();
            if (_selectedID == "," || _selectedID == "")
            {
                MessageBox.Show("Bạn chưa chọn nhân viên cần in danh sách!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (listRole.View)
            {
                //Lấy danh sách nhân viên chọn
                string fix_selectedID = _selectedID;
                if (fix_selectedID.StartsWith(","))
                    fix_selectedID = fix_selectedID.Substring(1);
                if (fix_selectedID.EndsWith(","))
                    fix_selectedID = fix_selectedID.Substring(0, fix_selectedID.Length - 1);


                //
                frmPreviewReport f = new frmPreviewReport("BHXHMau01a", new string[] { "Đề nghị cấp thẻ BHYT, BHXH", _month.ToString(), _year.ToString(),fix_selectedID });
                f.Show(this);
            }
            else
                MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void PrintToKhai(int EmployeeID, DateTime _From, DateTime _To)
        {
            LocalReport report = new LocalReport();
            Report2Printer prt = new Report2Printer();
            report.LoadReportDefinition(UISetting.GetEmbeddedFile("rptBHXH_ToKhai.rdlc"));
            ReportParameter r1, r2, r3;
            r1 = new ReportParameter("InsurancePlace", Program.strInsurancePlace);
            r2 = new ReportParameter("BranchName", Program.strBranch);
            r3 = new ReportParameter("BranchAddress", Program.strBranchAddress);
            report.SetParameters(new ReportParameter[] { r1, r2, r3 });
            prt.Landscape = false;
            EmployeeClient _wcf = Service.Employee();
            PremiumClient wcfPremium = Service.Premium();
            EmployeeInfo _Inf = new EmployeeInfo();
            _Inf = _wcf.Employee_GetInfo(EmployeeID);
            DataTable dt = wcfPremium.Premium_GetByDate(_From, _To, Program.strBranchCode, 2, _Inf.SIBookNo).Tables[0];
            report.DataSources.Add(new ReportDataSource("BaoCao_Premium", dt));

            string _sql = "";
            _sql += " SELECT * FROM (SELECT	* FROM vw_HRM_EmployeeActive) AS tmp1 LEFT OUTER JOIN ";
            _sql += " vw_HRM_LabourContract_Active ON tmp1.Employee_ID = vw_HRM_LabourContract_Active.LC_EmployeeID";
            _sql += " WHERE Employee_ID = " + EmployeeID.ToString();
            MainServiceClient wcfService = Service.MainService();
            DataTable dtEmpl = wcfService.Query(_sql).Tables[0];
            report.DataSources.Add(new ReportDataSource("BaoCao_Employee", dtEmpl));
            wcfService.Close();

            prt.Export(report);
            prt.CurrentPageIndex = 0;
            prt.Print(this);
        }
        
        private void btnInToKhai_Click(object sender, EventArgs e)
        {
            _selectedID = "";
            GetSelectedID();
            if (_selectedID == "," || _selectedID == "")
            {
                MessageBox.Show("Bạn chưa chọn nhân viên cần in tờ khai!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (listRole.View)
            {
                //frmTime frm = new frmTime(2);
                //if (frm.ShowDialog(this) == DialogResult.OK)
                //{
                DataGridViewRow dgvr = GetSelectedRow(dtgData.Rows);
                

                string SoBHXH = _SoBHXH != "" ? _SoBHXH : "Chờ cấp số";
                frmPreviewReport f = new frmPreviewReport("InToKhaiBHXH", new string[] { _selectedID, DateTime.Now.Date.ToString("dd/MM/yyyy"), dgvr.Cells["DoiSo_DenNgay"].Value.ToString(), SoBHXH });
                    f.Show(this);
                    //string[] Empl = _selectedID.Split(',');
                    //for (int i = 0; i < Empl.Length; i++)
                    //{
                    //    int _ID = 0;
                    //    if (Empl[i].Length > 0)
                    //    {
                    //        _ID = Convert.ToInt32(Empl[i]);
                    //        PrintToKhai(_ID, frm.FromDate, frm.ToDate);
                    //    }
                    //}
                //}
            }
            else
                MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private DataGridViewRow GetSelectedRow(DataGridViewRowCollection dataGridViewRowCollection)
        {
            DataGridViewRow retval = null;
            foreach (DataGridViewRow row in dataGridViewRowCollection)
                if (row.Cells["Check"].Value.ToString().ToLower() == "true")
                {
                    retval = row;
                    break;
                }
            return retval;
        }

        private void ChkCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAll.Checked)
            {
                for (int i = 0; i < dtgData.Rows.Count; i++)
                {
                    dtgData.Rows[i].Cells["Check"].Value = true;
                }
                GetSelectedID();
            }
            else
            {
                for (int i = 0; i < dtgData.Rows.Count; i++)
                {
                    dtgData.Rows[i].Cells["Check"].Value = false;
                }
                _selectedID = "";
            }
            
        }

        private void cbxLoaiDoiSo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //btnDuyet.Visible = cbxLoaiDoiSo.ComboBox.SelectedValue.ToString() == "P" && Program.isChuyenQuan;
            _selectedID = "";
            if (cbxLoaiDoiSo.ComboBox.SelectedValue.ToString() == "T")
                dtgData.MultiSelect = false;
            else
                dtgData.MultiSelect = true;
            showhide_commandbutton();
            Bind_Data();
        }

        //Chờ duyệt chốt sổ
        private void btnChoDuyet_Click(object sender, EventArgs e)
        {
            ChotSoInfo chotSo = null;
            dtgData.EndEdit();
            foreach (DataGridViewRow row in dtgData.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value))
                {
                    chotSo = new ChotSoInfo();
                    chotSo.ChotSo_BranchID = Program.intBranchID;
                    chotSo.ChotSo_EmployeeID = Globals.Object_GetValue<int>(row.Cells["Employee_Id"].Value);
                    chotSo.ChotSo_HoVaTen = Globals.Object_GetValue<string>(row.Cells["Employee_FullName"].Value);
                    chotSo.ChotSo_SoSo = Globals.Object_GetValue<string>(row.Cells["Employee_SiBookNo"].Value);
                    chotSo.ChotSo_Loai = "P"; //cbxLoaiDoiSo.ComboBox.SelectedValue.ToString();
                    //
                    ChotSo_Controller.Instance().ChotSo_Insert(chotSo);
                }
            }
            //
            Bind_Data();
        }

        private void btnDuyet_Click(object sender, EventArgs e)
        {
            ChotSoInfo chotSo = null;
            dtgData.EndEdit();
            foreach (DataGridViewRow row in dtgData.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value))
                {
                    chotSo = new ChotSoInfo();
                    chotSo.ChotSo_BranchID = Program.intBranchID;
                    chotSo.ChotSo_ID = Globals.Object_GetValue<int>(row.Cells["ChotSo_Id"].Value);
                    chotSo.ChotSo_EmployeeID = Globals.Object_GetValue<int>(row.Cells["Employee_Id"].Value);
                    chotSo.ChotSo_HoVaTen = Globals.Object_GetValue<string>(row.Cells["Employee_FullName"].Value);
                    chotSo.ChotSo_SoSo = Globals.Object_GetValue<string>(row.Cells["Employee_SiBookNo"].Value);
                    chotSo.ChotSo_Loai = "D"; // Duyệt chốt sổ
                    //
                    ChotSo_Controller.Instance().ChotSo_Update(chotSo);
                }
            }
            
            //Refresh data danh sách employ
            LocalDB.dtTableEmployee = _wcfEmpl.Employee_GetAllWithBranch(Program.intBranchID).Tables[0];
            //
            Bind_Data();
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            dtgData.EndEdit();
            foreach (DataGridViewRow row in dtgData.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value))
                {
                    ChotSo_Controller.Instance().ChotSo_Delete(Globals.Object_GetValue<int>(row.Cells["ChotSo_Id"].Value));
                }
            }
            //
            Bind_Data();
        }
        private void showhide_commandbutton()
        {
            btnDel.Visible = true;
            btnChoDuyet.Visible = true;
            btnDuyet.Visible = true;
            btnCapso.Visible = true;
            switch (cbxLoaiDoiSo.ComboBox.SelectedValue.ToString())
            {
                case "T":
                    btnDel.Visible = false;
                    btnDuyet.Visible = false;
                    btnCapso.Visible = false;
                    btnPrint.Visible = false;
                    break;
                case "P":
                    btnDel.Visible = true;
                    btnChoDuyet.Visible = false;
                    btnDuyet.Visible = Program.isChuyenQuan;
                    btnCapso.Visible = false;
                    btnPrint.Visible = true;
                    break;
                case "D":
                    btnDel.Visible = false;
                    btnChoDuyet.Visible = false;
                    btnDuyet.Visible = false;
                    btnCapso.Visible = false;
                    btnPrint.Visible = false;
                    break;
                case "C":
                    btnDel.Visible = Program.isChuyenQuan;
                    btnChoDuyet.Visible = false;
                    btnDuyet.Visible = false;
                    btnCapso.Visible = false;
                    break;
            }
        }

        private void btnCapso_Click(object sender, EventArgs e)
        {
            _selectedID = "";
            GetSelectedID();
            if (_selectedID == "," || _selectedID == "")
            {
                MessageBox.Show("Bạn chưa chọn nhân viên cấp sổ!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            wcfDoiSo.HRM_Doiso_CapNhatDeNghiCapSo(Program.intBranchID, "C", _selectedID.StartsWith(",") ? _selectedID.Substring(1) : _selectedID, "",DateTime.Now);
            _selectedID = "";
            Bind_Data();          
         
        }

        private void btnFind_Click_1(object sender, EventArgs e)
        {
            btnFind_Click(null, null);
        }

        private void dgvIssueInsBookList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
           
        }

        private void inTờKhaiMẫuMớiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _selectedID = "";
            GetSelectedID();
            if (_selectedID == "," || _selectedID == "")
            {
                MessageBox.Show("Bạn chưa chọn nhân viên cần in tờ khai!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (listRole.View)
            {
                
                DataGridViewRow dgvr = GetSelectedRow(dtgData.Rows);
                string SoBHXH = _SoBHXH != "" ? _SoBHXH : "Chờ cấp số";
                frmPreviewReport f = new frmPreviewReport("InToKhaiBHXH_Maumoi", new string[] { _selectedID, DateTime.Now.Date.ToString("dd/MM/yyyy"), dgvr.Cells["DoiSo_DenNgay"].Value.ToString(), SoBHXH });
                f.Show(this);                
            }
            else
                MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void inPhụLụcMẫuA01TSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _selectedID = "";
            string _SoSoBHXH = "";
            int Counter = 0;
            //
            dtgData.EndEdit();
            foreach (DataGridViewRow row in dtgData.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value))
                {
                    _selectedID = row.Cells["Employee_ID"].Value.ToString();
                    _SoSoBHXH = row.Cells["Employee_SIBookNo"].Value.ToString();
                    Counter++;
                }
                if (Counter > 1)
                        break;
            }
            //

            if (_selectedID == "," || _selectedID == "")
            {
                MessageBox.Show("Bạn chưa chọn nhân viên cần in tờ khai!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if( _selectedID.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries).Length > 1)
            {
                MessageBox.Show("Bạn chỉ được chọn 1 nhân viên để in phụ lục!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (listRole.View)
            {
                frmPreviewReport f = new frmPreviewReport("InPhuLucBHXH", new string[] { _SoSoBHXH});
                f.Show(this);
            }
            else
                MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void mnuPrintChoDuyet_Click(object sender, EventArgs e)
        {
            frmPreviewReport f = new frmPreviewReport("InDanhSachChoDuyet", new string[] { Program.intBranchID.ToString(), "P" });
            f.Show(this);
        }
    }
}
